<template>
  <div class="container">
    <Breadcrumb :items="['平台管理', '服务器管理']" />
    <a-card class="general-card" :title="$t('服务器管理')">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            label-align="left"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-layout="inline"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="serverName" :label="$t('服务器名称')">
                  <a-input
                    v-model="searchForm.serverName"
                    :placeholder="$t('请输入服务器名称')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" :label="$t('状态')">
                  <a-select
                    v-model="searchForm.status"
                    :placeholder="$t('请选择状态')"
                    allow-clear
                  >
                    <a-option :value="1">{{ $t('启用') }}</a-option>
                    <a-option :value="0">{{ $t('禁用') }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-space>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ $t('搜索') }}
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    {{ $t('重置') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 32px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-button type="primary" @click="openAddDialog">
            <template #icon>
              <icon-plus />
            </template>
            {{ $t('新增') }}
          </a-button>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-table
        row-key="id"
        :loading="loading"
        :data="renderData"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        :bordered="false"
      >
        <template #columns>
          <a-table-column title="服务器名称" data-index="serverName" />
          <a-table-column title="服务器IP" data-index="serverIp" />
          <a-table-column title="服务器端口" data-index="serverPort" />
          <a-table-column title="平台名称" data-index="platformName" />
          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              <a-tag :color="record.status === 1 ? 'green' : 'red'">
                {{ record.status === 1 ? '启用' : '禁用' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="createTime">
            <template #cell="{ record }">
              {{ record.createTime && typeof record.createTime === 'string' 
                ? record.createTime.replace('T', ' ').substring(0, 19) 
                : '' }}
            </template>
          </a-table-column>
          <a-table-column title="备注" data-index="remark" />
          <a-table-column title="操作" fixed="right" :width="150">
            <template #cell="{ record }">
              <a-button
                type="text"
                size="small"
                @click="openEditDialog(record)"
              >
                编辑
              </a-button>
              <a-button
                type="text"
                status="danger"
                size="small"
                @click="handleDelete(record)"
              >
                删除
              </a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="visible"
      :title="isEdit ? '编辑服务器' : '新增服务器'"
      @before-ok="handleSubmit"
      @close="() => { console.log('对话框关闭'); }"
      @cancel="() => { console.log('对话框取消'); }"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-align="right"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
      >
        <a-form-item field="serverName" label="服务器名称" required>
          <a-input v-model="form.serverName" placeholder="请输入服务器名称" />
        </a-form-item>
        <a-form-item field="serverIp" label="服务器IP" required>
          <a-input v-model="form.serverIp" placeholder="请输入服务器IP" />
        </a-form-item>
        <a-form-item field="serverPort" label="服务器端口" required>
          <a-input-number
            v-model="form.serverPort"
            placeholder="请输入服务器端口"
            :min="1"
            :max="65535"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item field="status" label="状态">
          <a-radio-group v-model="form.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="platformId" label="平台">
          <a-select
            v-model="form.platformId"
            :placeholder="$t('请选择平台')"
            allow-clear
          >
            <a-option
              v-for="platform in platformList"
              :key="platform.id"
              :value="platform.id"
            >
              {{ platform.platformName }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="remark" label="备注">
          <a-textarea v-model="form.remark" placeholder="请输入备注" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, onMounted } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import {
    getServerPage,
    addServer,
    updateServer,
    deleteServer,
    getPlatformList,
    ServerItem,
    PlatformItem,
    ApiResponse,
  } from '@/api/server';
  import useLoading from '@/hooks/loading';
  import { cloneDeep } from 'lodash';

  const { loading, setLoading } = useLoading();
  const visible = ref(false);
  const isEdit = ref(false);
  const formRef = ref();
  const serverList = ref<ServerItem[]>([]);
  const platformList = ref<PlatformItem[]>([]);
  
  const searchForm = reactive({
    serverName: '',
    status: undefined,
  });
  
  const form = reactive({
    id: '',
    serverName: '',
    serverIp: '',
    serverPort: 8080,
    status: 1,
    platformId: undefined as (number | string | undefined),
    remark: '',
  });
  
  const pagination = reactive({
    total: 0,
    current: 1,
    pageSize: 10,
  });
  
  const rules = {
    serverName: [{ required: true, message: '请输入服务器名称' }],
    serverIp: [{ required: true, message: '请输入服务器IP' }],
    serverPort: [{ required: true, message: '请输入服务器端口' }],
    platformId: [{ required: true, message: '请选择平台' }],
  };

  const renderData = computed(() => {
    console.log('渲染数据:', serverList.value);
    return serverList.value;
  });

  async function fetchData() {
    setLoading(true);
    try {
      const params = {
        current: pagination.current,
        size: pagination.pageSize,
        serverName: searchForm.serverName || undefined,
        status: searchForm.status,
      };
      
      console.log('查询参数:', params);
      
      const res = await getServerPage(params);
      console.log('获取服务器列表响应:', res);
      
      if (!res) {
        console.error('响应数据为空或格式不正确:', res);
        Message.error('获取服务器列表失败: 响应数据格式不正确');
        setLoading(false);
        return;
      }
      
      if (res.code === 200 && res.data) {
        // 检查返回的数据结构
        console.log('服务器列表原始数据:', res.data);
        
        // 处理分页数据
        if (res.data.records && Array.isArray(res.data.records)) {
          // 处理数据，移除可能存在的换行符
          const processedRecords = res.data.records.map((item: any) => ({
            ...item,
            // 移除IP地址中可能存在的换行符
            serverIp: item.serverIp ? item.serverIp.replace(/\r?\n/g, '').trim() : '',
          }));
          
          // 使用处理后的数据
          serverList.value = processedRecords;
          pagination.total = res.data.total || 0;
          pagination.current = res.data.current || 1;
          pagination.pageSize = res.data.size || 10;
          console.log('服务器列表数据处理完成:', serverList.value);
        } else {
          console.error('服务器列表数据格式不正确:', res.data);
          Message.error('获取服务器列表失败: 数据格式不正确');
        }
      } else {
        console.error('获取服务器列表失败:', res);
        Message.error(`获取服务器列表失败: ${res.message || '未知错误'}`);
      }
    } catch (err) {
      console.error('获取服务器列表异常:', err);
      Message.error('获取服务器列表失败: ' + (err instanceof Error ? err.message : '未知错误'));
    } finally {
      setLoading(false);
    }
  }

  function search() {
    pagination.current = 1;
    fetchData();
  }

  function reset() {
    searchForm.serverName = '';
    searchForm.status = undefined;
    pagination.current = 1;
    fetchData();
  }

  function onPageChange(current: number) {
    pagination.current = current;
    fetchData();
  }

  function onPageSizeChange(pageSize: number) {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
  }

  async function fetchPlatformList() {
    try {
      const res = await getPlatformList();
      if (res.code === 200 && Array.isArray(res.data)) {
        platformList.value = res.data;
      } else {
        console.error('获取平台列表失败:', res);
        Message.error('获取平台列表失败');
      }
    } catch (err) {
      console.error('获取平台列表异常:', err);
      Message.error('获取平台列表失败');
    }
  }

  function openAddDialog() {
    isEdit.value = false;
    Object.assign(form, {
      id: '',
      serverName: '',
      serverIp: '',
      serverPort: 8080,
      status: 1,
      platformId: undefined,
      remark: '',
    });
    fetchPlatformList();
    visible.value = true;
  }

  function openEditDialog(record: ServerItem) {
    console.log('打开编辑对话框，记录:', record);
    isEdit.value = true;
    console.log('设置isEdit为:', isEdit.value);
    Object.assign(form, {
      id: record.id,
      serverName: record.serverName,
      serverIp: record.serverIp,
      serverPort: record.serverPort,
      status: record.status,
      platformId: record.platformId,
      remark: record.remark || '',
    });
    console.log('编辑表单数据:', form);
    fetchPlatformList();
    visible.value = true;
  }

  async function handleSubmit() {
    console.log('提交表单，当前编辑状态:', isEdit.value);
    
    try {
      // 检查formRef是否存在
      if (!formRef.value) {
        console.error('表单引用不存在');
        return false;
      }
      
      // 修改验证方式，使用try-catch捕获可能的错误
      try {
        await formRef.value.validate();
        console.log('表单验证通过');
      } catch (validationError) {
        console.error('表单验证失败:', validationError);
        return false;
      }
      
      // 构建提交数据
      const submitData = {
        ...form,
        // 确保数值类型正确
        serverPort: Number(form.serverPort),
        status: Number(form.status),
      };
      
      console.log('提交服务器数据:', submitData);
      console.log('isEdit状态:', isEdit.value);
      
      let res;
      if (isEdit.value) {
        console.log('调用updateServer接口');
        res = await updateServer(submitData);
      } else {
        console.log('调用addServer接口');
        res = await addServer(submitData);
      }
      
      console.log('提交服务器响应:', res);
      
      if (res.code === 200) {
        // 显示成功消息
        const successMsg = isEdit.value ? '更新成功' : '添加成功';
        Message.success(successMsg);
        fetchData();
        visible.value = false; // 关闭对话框
        return true;
      } else {
        Message.error(`${isEdit.value ? '更新' : '添加'}失败: ${res.message || '未知错误'}`);
        return false;
      }
    } catch (err) {
      console.error(`${isEdit.value ? '更新' : '添加'}服务器异常:`, err);
      Message.error(isEdit.value ? '更新失败' : '添加失败');
      return false;
    }
  }

  function handleDelete(record: ServerItem) {
    // 确保id存在且类型正确
    if (!record.id) {
      Message.error('服务器ID不存在，无法删除');
      return;
    }
    
    const id: string | number = record.id;
    
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除服务器 "${record.serverName}" 吗？`,
      onOk: async () => {
        try {
          const res = await deleteServer(id);
          console.log('删除服务器响应:', res);
          
          if (res.code === 200) {
            Message.success('删除成功');
            fetchData();
          } else {
            Message.error(`删除失败: ${res.message || '未知错误'}`);
          }
        } catch (err) {
          console.error('删除服务器异常:', err);
          Message.error('删除失败');
        }
      },
    });
  }

  onMounted(() => {
    fetchData();
    fetchPlatformList();
  });
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }
  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }
  .setting {
    display: flex;
    align-items: center;
    width: 200px;
  }
</style> 